/* NOTICE
 
    Jim - the Java Image Manager, copyright (c) 2005 - 2007 Grant Gardner 
 
    Jim is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Jim is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
  
    In addition, as a special exception, you are permitted to link this code
    with the 3rd party libraries required to compile this file and to
    distribute a linked combination including them. You must obey the
    GNU General Public License in all respects for all of the code except for
    those 3rd party libraries that are licenced under terms incompatible with the
    GNU General Public License.  
 
 
 NOTICE */

package au.com.lastweekend.jim.io.exif;

import org.apache.log4j.Logger;

import au.com.lastweekend.jim.io.exif.makernote.MakernoteException;
import au.com.lastweekend.jim.io.exif.makernote.MakernoteReader;
import au.com.lastweekend.jim.io.exif.makernote.MakernoteRegistry;
import au.com.lastweekend.jim.io.metadata.Directory;

/**
 * 
 * 
 * @version $Id: ExifDirectoryReader.java,v 1.2 2005/06/09 11:15:37 ggardner Exp $
 * @author <a href="mailto:grant@lastweekend.com.au"> <Grant Gardner> </a>
 */
public class ExifDirectoryReader extends AbstractTiffTagReader {

    private static final Logger LOG = Logger.getLogger(ExifDirectoryReader.class);

    /**
     * @param data
     */
    public ExifDirectoryReader(byte[] data) {

        super(data);
    }

    @Override
    public Directory extract(Directory parentDirectory) throws TiffTagProcessingException {

        setDirectory(new ExifDirectory(parentDirectory));
        processTiffTags();
        return getDirectory();
    }

    /**
     * 
     * @see au.com.lastweekend.jim.io.exif.AbstractTiffTagReader#getLinkedDirectoryReader()
     */
    @Override
    protected AbstractTiffTagReader getLinkedDirectoryReader() {

        return null;
    }

    /**
     * 
     * @see au.com.lastweekend.jim.io.exif.AbstractTiffTagReader#processTag(int, int, int, int)
     */
    @Override
    protected void processTag(int tagType, int formatCode, int componentCount, int tagValueOffset)
            throws TiffTagProcessingException {

        switch (tagType) {
            case ExifDirectory.TAG_MAKER_NOTE :
                extractMakerNote(tagType, formatCode, componentCount, tagValueOffset);
                break;
            case ExifDirectory.TAG_INTEROP_OFFSET :
                processSubDirectory(new ExifInteropDirectoryReader(getData()), tagType, formatCode, componentCount, tagValueOffset);
                break;
            case ExifDirectory.TAG_USER_COMMENT :
                extractUserComment(tagType, formatCode, componentCount, tagValueOffset);
                break;
            default :
                super.processTag(tagType, formatCode, componentCount, tagValueOffset);
        }
    }

    /**
     * @param tagType
     * @param formatCode
     * @param componentCount
     * @param tagValueOffset
     */
    private void extractUserComment(int tagType, int formatCode, int componentCount, int tagValueOffset)
            throws TiffTagProcessingException {

        Object tagValue = getDataFormat().parse(getData(), formatCode, componentCount, tagValueOffset);

        if (tagValue instanceof String) {
            tagValue = readCommentString((String) tagValue, tagValueOffset, componentCount, formatCode);
        }

    }

    /**
     * A special case of readString that handle Exif UserComment reading. This method is necessary as certain camere models prefix
     * the comment string with "ASCII\0", which is all that would be returned by readString(...).
     */
    private String readCommentString(String rawValue, int tagValueOffset, int componentCount, int formatCode)
            throws TiffTagProcessingException {

        // Olympus has this padded with trailing spaces.

        /*
         * drew's code did this to remove these first, but I don't think we need that now. // ArrayIndexOutOfBoundsException bug
         * fixed by Hendrik W?rdehoff - 20 Sep 2002 int byteCount = componentCount * TiffTagFormat.getBytesPerFormat(formatCode);
         * for (int i = byteCount - 1; i >= 0; i--) { if (_data[tagValueOffset + i] == ' ') { _data[tagValueOffset + i] = (byte)
         * '\0'; } else { break; } }
         */
        // Copy the comment, strip the leading "ASCII" identifier from the
        // comment.
        byte[] data = getData();

        if (rawValue.startsWith("ASCII")) {
            for (int i = 5; i < 10; i++) {
                byte b = data[tagValueOffset + i];
                if (b != '\0' && b != ' ') {
                    return (String) getDataFormat().parse(data, formatCode, componentCount - i, tagValueOffset + i);
                }
            }
        }

        // TODO implement support for UNICODE and JIS UserComment encodings..?
        // Writing the comment may lose this information.

        return rawValue;
    }

    private void extractMakerNote(int tagType, int formatCode, int componentCount, int tagValueOffset)
            throws TiffTagProcessingException {

        MakernoteReader reader = MakernoteRegistry.getReader((ExifDirectory) getDirectory(), getDataFormat(), getData(),
                formatCode, componentCount, tagValueOffset);
        Directory makernoteDirectory;
        try {
            makernoteDirectory = reader.extractMakernote(getDirectory());
        } catch (MakernoteException e) {
            LOG.warn("Error reading makernote, treating as unknown", e);
            reader = MakernoteRegistry.getUnknownMakernoteReader((ExifDirectory) getDirectory(), getDataFormat(), getData(),
                    formatCode, componentCount, tagValueOffset);
            try {
                makernoteDirectory = reader.extractMakernote(getDirectory());
            } catch (MakernoteException e1) {
                // OK, now we are in trouble.
                throw new TiffTagProcessingException("Can't use unkownMakernoteReader to reader makernote data", e1);
            }
        }
        getDirectory().addSubDirectory(tagType, formatCode, makernoteDirectory);
    }
}